﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace SlideshowGenerator
{
    public partial class Frm_Main : Form
    {
        private Slideshow _slideshow;

        private OpenFileDialog _openCaptionImageFileDialog;
        private OpenFileDialog _openSlideshowImageFileDialog;
        private List<string> _captionImagePaths = new List<string>();

        public List<string> CaptionImagePath
        {
            get { return _captionImagePaths; }
            set { _captionImagePaths = value; }
        }
        private List<string> _slideshowImagesPath;

        private FolderBrowserDialog _folderBrowserDialog;

        public Frm_Main()
        {
            Frm_Splashscreen splashScreen = new Frm_Splashscreen();
            splashScreen.ShowDialog(this);

            //Load Configuration
            Configuration.LoadConfiguration();

            //if first execution, show language selection
            if (!File.Exists(String.Format("{0}\\notFirstExecution", Application.StartupPath)))
            {
                Frm_LanguageSelection languageSelection = new Frm_LanguageSelection();
                languageSelection.ShowDialog(this);
                File.Create(String.Format("{0}\\notFirstExecution", Application.StartupPath));
            }

            switch (Configuration.Language)
            {
                case Configuration.Languages.English:
                    Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en");
                    break;
                case Configuration.Languages.Turkish:
                    Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("tr");
                    break;
                default:
                    Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en");
                    MessageBox.Show("Error loading the language.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
            }

            InitializeComponent();
            _slideshowImagesPath = new List<string>();
            _slideshow = new Slideshow();
            this.tbl_images.DataSource = _slideshow.SlideshowImagesTable;
            SetGridAppearrance();
        }

        private void btn_browseCapImg_Click(object sender, EventArgs e)
        {
            OpenCaptionImage();
        }

        private void OpenCaptionImage()
        {
            _openCaptionImageFileDialog = new OpenFileDialog();
            _openCaptionImageFileDialog.CheckFileExists = true;
            _openCaptionImageFileDialog.Multiselect = true;
            _openCaptionImageFileDialog.Filter = Properties.Resources.text_ofdImageFilter;
            _openCaptionImageFileDialog.RestoreDirectory = true;
            _openCaptionImageFileDialog.Title = Properties.Resources.text_openCaptionImage;

            DialogResult dr = _openCaptionImageFileDialog.ShowDialog();

            if (dr == DialogResult.OK)
            {
                //clear list
                _captionImagePaths.Clear();

                //add new paths
                string filenamesString = String.Empty;
                foreach (string filename in _openCaptionImageFileDialog.FileNames)
                {
                    filenamesString = String.Format("{0}\"{1}\" ", filenamesString, filename);
                    this._captionImagePaths.Add(filename);
                }
                this.tbx_capImg.Text = filenamesString;
            }
        }

        private void btn_browseSldImgs_Click(object sender, EventArgs e)
        {
            OpenSlideShowImages();
        }

        private void OpenSlideShowImages()
        {
            _openSlideshowImageFileDialog = new OpenFileDialog();
            _openSlideshowImageFileDialog.CheckFileExists = true;
            _openSlideshowImageFileDialog.Filter = Properties.Resources.text_ofdImageFilter;
            _openSlideshowImageFileDialog.Multiselect = true;
            _openSlideshowImageFileDialog.RestoreDirectory = true;
            _openSlideshowImageFileDialog.Title = Properties.Resources.text_openSlideshowImage;
            
            DialogResult dr = _openSlideshowImageFileDialog.ShowDialog();

            if (dr == DialogResult.OK)
            {
                //set tbx text
                foreach (string file in _openSlideshowImageFileDialog.FileNames)
                {
                    this.tbx_slideImgs.Text += String.Format("\"{0}\" ", file);
                }
                if (_openSlideshowImageFileDialog.FileNames.Length > 0)
                {
                    this.tbx_slideImgs.Text.Remove(this.tbx_slideImgs.Text.Length - 1, 1);
                }

                //clear list
                _slideshowImagesPath.Clear();

                //add images to list
                foreach (string imgPath in _openSlideshowImageFileDialog.FileNames)
                {
                    this._slideshowImagesPath.Add(imgPath);
                }
            }
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            AddToSlideshow();
        }

        private void AddToSlideshow()
        {
            if (_captionImagePaths.Count > 0)
            {
                if (_slideshow == null)
                {
                    _slideshow = new Slideshow();
                    this.tbl_images.DataSource = _slideshow.SlideshowImagesTable;
                    SetGridAppearrance();
                }

                _slideshow.AddImages(new List<string>(this._captionImagePaths), new List<string>(this._slideshowImagesPath));
            }
            else
            {
                MessageBox.Show(Properties.Resources.mb_selectCaptionImage,
                    Properties.Resources.mb_Info, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void GridCMS_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem == GridCMS.Items["menu_del"])
            {
                DeleteSelectedSlideshowImages();
            }
        }

        private void DeleteSelectedSlideshowImages()
        {
            List<int> rowsToDelete = new List<int>();
            foreach (DataGridViewRow dgr in tbl_images.SelectedRows)
            {
                rowsToDelete.Add(dgr.Index);
            }
            _slideshow.DeleteSelectedImages(rowsToDelete);
            tbl_images.Update();
        }

        private void btn_browseOutput_Click(object sender, EventArgs e)
        {
            _folderBrowserDialog = new FolderBrowserDialog();
            _folderBrowserDialog.Description = Properties.Resources.text_chooseFolder;
            _folderBrowserDialog.RootFolder = Environment.SpecialFolder.Desktop;
            _folderBrowserDialog.ShowNewFolderButton = true;

            DialogResult dr = _folderBrowserDialog.ShowDialog();

            if (dr == DialogResult.OK && Directory.Exists(_folderBrowserDialog.SelectedPath))
            {
                this.tbx_output.Text = _folderBrowserDialog.SelectedPath;
                _slideshow.OutputPath = _folderBrowserDialog.SelectedPath;
            }
        }

        private void btn_createSlideshow_Click(object sender, EventArgs e)
        {
            if (_slideshow.SlideshowImagesTable.Rows.Count > 0)
            {
                if (_slideshow.OutputPath != String.Empty)
                {
                    Frm_SlideshowCreation slideShowCreation = new Frm_SlideshowCreation(_slideshow);
                    slideShowCreation.ShowDialog(this);
                }
                else
                {
                    MessageBox.Show(Properties.Resources.mb_chooseOutput, Properties.Resources.mb_Info,
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show(Properties.Resources.mb_notSelectedImages, Properties.Resources.mb_Info,
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btn_reset_Click(object sender, EventArgs e)
        {
            ResetSlideshow();
        }

        private void ResetSlideshow()
        {
            if (MessageBox.Show(Properties.Resources.mb_resetSlideshow, Properties.Resources.mb_resetSlideshowCaption,
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                tbl_images.DataSource = null;
                tbx_capImg.ResetText();
                tbx_output.ResetText();
                tbx_slideImgs.ResetText();
                tbl_images.Update();
                _captionImagePaths.Clear();
                _slideshowImagesPath.Clear();
                _slideshow = new Slideshow();
                this.tbl_images.DataSource = _slideshow.SlideshowImagesTable;
                SetGridAppearrance();
            }
        }

        private void SetGridAppearrance()
        {
            tbl_images.Columns[Slideshow.TableColumnNames.ID].ReadOnly = true;
            tbl_images.Columns[Slideshow.TableColumnNames.ID].Resizable = DataGridViewTriState.False;
            tbl_images.Columns[Slideshow.TableColumnNames.ID].SortMode = DataGridViewColumnSortMode.NotSortable;
            tbl_images.Columns[Slideshow.TableColumnNames.ID].Width = 30;
            tbl_images.Columns[Slideshow.TableColumnNames.ID].HeaderText = "";

            tbl_images.Columns[Slideshow.TableColumnNames.CaptionImages].ReadOnly = true;
            tbl_images.Columns[Slideshow.TableColumnNames.CaptionImages].Resizable = DataGridViewTriState.False;
            tbl_images.Columns[Slideshow.TableColumnNames.CaptionImages].SortMode = DataGridViewColumnSortMode.NotSortable;
            tbl_images.Columns[Slideshow.TableColumnNames.CaptionImages].Width = 300;
            tbl_images.Columns[Slideshow.TableColumnNames.CaptionImages].HeaderText = Properties.Resources.gh_captionImages;

            tbl_images.Columns[Slideshow.TableColumnNames.CaptionImageFrequency].Resizable = DataGridViewTriState.False;
            tbl_images.Columns[Slideshow.TableColumnNames.CaptionImageFrequency].SortMode = DataGridViewColumnSortMode.NotSortable;
            tbl_images.Columns[Slideshow.TableColumnNames.CaptionImageFrequency].Width = 195;
            tbl_images.Columns[Slideshow.TableColumnNames.CaptionImageFrequency].HeaderText = Properties.Resources.gh_capImageFreq;

            tbl_images.Columns[Slideshow.TableColumnNames.NumberOfImages].ReadOnly = true;
            tbl_images.Columns[Slideshow.TableColumnNames.NumberOfImages].Resizable = DataGridViewTriState.False;
            tbl_images.Columns[Slideshow.TableColumnNames.NumberOfImages].SortMode = DataGridViewColumnSortMode.NotSortable;
            tbl_images.Columns[Slideshow.TableColumnNames.NumberOfImages].Width = 195;
            tbl_images.Columns[Slideshow.TableColumnNames.NumberOfImages].HeaderText = Properties.Resources.gh_numberImages;
        }

        private void btn_options_Click(object sender, EventArgs e)
        {
            Frm_Configuration config = new Frm_Configuration();
            config.ShowDialog(this);
        }

        private void tbl_images_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1 && e.ColumnIndex == tbl_images.Columns[Slideshow.TableColumnNames.CaptionImageFrequency].Index)
            {
                int capImgFreq;
                if (Int32.TryParse(tbl_images.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), out capImgFreq))
                {
                    _slideshow.ChangeCaptionImageFrequency(Convert.ToInt32(tbl_images.Rows[e.RowIndex].Cells[Slideshow.TableColumnNames.ID].Value), capImgFreq);
                }
                else
                {
                    DialogResult dr = MessageBox.Show(Properties.Resources.mb_noValidNumericValue, Properties.Resources.mb_Info,
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (dr == DialogResult.Yes)
                    {
                        tbl_images.Rows[e.RowIndex].Cells[e.ColumnIndex].KeyEntersEditMode(new KeyEventArgs(Keys.Delete));
                    }
                    else
                    {
                        tbl_images.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Configuration.CaptionImageFrequency;
                    }
                }
            }
        }

        private void btn_info_Click(object sender, EventArgs e)
        {
            Frm_Info info = new Frm_Info();
            info.ShowDialog(this);
        }

        private void btn_createCapImg_Click(object sender, EventArgs e)
        {
            Frm_CaptionImageCreator captionImageCreator = new Frm_CaptionImageCreator();
            captionImageCreator.ShowDialog(this);
        }

        private void Frm_Main_Shown(object sender, EventArgs e)
        {
            this.Location = new Point((Screen.PrimaryScreen.Bounds.Width / 2) - (this.Width / 2),
                (Screen.PrimaryScreen.Bounds.Height / 2) - (this.Height / 2));
        }

        private void btn_resetSsImages_Click(object sender, EventArgs e)
        {
            _slideshowImagesPath.Clear();
            this.tbx_slideImgs.Text = String.Empty;
        }
    }
}
